/**
 * @author Semika siriwardana(semika.siriwardana@gmail.com)
 */
(function($){
	$.cometNotify = {
		
		_connected:false,
		loginUserName:undefined,
		uuid:undefined,
		_disconnecting:undefined,
		_chatSubscription:undefined,
		_membersSubscription:undefined,
		_notifySubscription:undefined,
		memberListContainerID:undefined, //'id' of a 'div' or 'span' tag which keeps list of online users.
		
		/**
		 * This method can be invoked to disconnect from the chat server.
		 * When user logging off or user close the browser window, user should
		 * be disconnected from cometd server.
		 */
		leave: function() {
            $.cometd.batch(function() {
                $.cometNotify._unsubscribe();
            });
            $.cometd.disconnect();

            $.cometNotify.loginUserName  = null;
            $.cometNotify._disconnecting = true;
        },
		
        /**
         * Handshake with the server. When user logging into your system, you can call this method
         * to connect that user to cometd server. With that user will subscribe with tow channel.
         * '/chat/demo' and '/members/demo' and start to listen to those channels. 
         */
		join: function(opinion) {
			
			$.cometNotify._disconnecting = false;
			$.cometNotify.loginUserName  = opinion.username;
			$.cometNotify.uuid = opinion.uuid;
            var cometdURL = opinion.url;
            $.cometd.websocketEnabled = false;
            $.cometd.websocketEnabled = $.cometNotify._checkWebsocketEnable();
            $.cometd.configure({
                url: cometdURL,
                logLevel: 'debug'
            });
            
            //$.cometd.websocketEnabled = false;
            $.cometd.handshake();
		},	 
               
        
        notify :function(message) {
        	if(message.data.type!="notify") return;
			$("#notifyContent").append("<div>"+message.data.message+"</div>");
        },
        
        _unsubscribe: function() {
            if ($.cometNotify._chatSubscription) {
                $.cometd.unsubscribe($.cometNotify._chatSubscription);
            }
            $.cometNotify._chatSubscription = null;
            
            if ($.cometNotify._membersSubscription) {
                $.cometd.unsubscribe($.cometNotify._membersSubscription);
            }
            $.cometNotify._membersSubscription = null;
            
            if($.cometNotify._notifySubscription){
            	$.cometd.unsubscribe($.cometNotify._notifySubscription);
            }
            $.cometNotify._notifySubscription = null;
        },
        
        _connectionEstablished: function() {
            // connection establish (maybe not for first time), so just
            // tell local user and update membership
            $.cometd.publish('/service/members', {
                user: $.cometNotify.loginUserName,
                uuid: $.cometNotify.uuid
            });
        },
        
        _connectionBroken: function() {
            $('#' + $.cometNotify.memberListContainerID).empty();
        },
        
        _connectionClosed: function() {
           /* $.cometNotify.receive({
                data: {
                    user: 'system',
                    chat: 'Connection to Server Closed'
                }
            });*/
        },
        
        _metaConnect: function(message) {
            if ($.cometNotify._disconnecting) {
            	$.cometNotify._connected = false;
            	$.cometNotify._connectionClosed();
            } else {
                var wasConnected = $.cometNotify._connected;
                $.cometNotify._connected = message.successful === true;
                if (!wasConnected && $.cometNotify._connected) {
                	$.cometNotify._connectionEstablished();
                } else if (wasConnected && !$.cometNotify._connected) {
                	$.cometNotify._connectionBroken();
                }
            }
        },
        
        _subscribe: function() {
			$.cometNotify._notifySubscription    = $.cometd.subscribe('/notify/system',    $.cometNotify.notify); //channel handling chat messages
        },
        
        _connectionInitialized: function() {
            // first time connection for this client, so subscribe tell everybody.
            $.cometd.batch(function() {
            	$.cometNotify._subscribe();
            });
        },
        
		_metaHandshake: function (message) {
            if (message.successful) {
            	$.cometNotify._connectionInitialized();
            }
        },
        
		_initListeners: function() {
			$.cometd.addListener('/meta/handshake', $.cometNotify._metaHandshake);
	        $.cometd.addListener('/meta/connect',   $.cometNotify._metaConnect);
	        
	        $(window).unload(function() {
	        	$.cometd.reload();
                $.cometd.disconnect();
	        });
		},
		
		_checkWebsocketEnable:function(){
			window.WebSocket = window.WebSocket || window.MozWebSocket;
			if (!window.WebSocket)return false;
			return true;
		},
			
		onLoad: function(config) {
			$.cometNotify.memberListContainerID = config.memberListContainerID;
			$.cometNotify._initListeners();
		}		
	};
	
})(jQuery);
